package com.example.taluo.mapper;

import com.example.taluo.entity.User;
import com.example.taluo.entity.dto.gamedto.UserRanking;
import org.apache.ibatis.annotations.*;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.stereotype.Component;

import java.util.List;

/*** @Author supersaiya
 * @Description TODO

 * @Date 2025/2/15 16:21

 * @Version 1.0*/
@Mapper
public interface UserMapper {

    // 查询所有用户
    @Select("SELECT * FROM User")
    List<User> getAllUsers();

    // 根据 ID 查询用户
    @Select("SELECT * FROM User WHERE id = #{id}")
    User getUserById(@Param("id") Integer id);

    // 添加用户
    @Insert("INSERT INTO User (username, password, eloRating, wins, losses, draws, status, lastLogin, addTime, updateTime) " +
            "VALUES (#{username}, #{password}, #{eloRating}, #{wins}, #{losses}, #{draws}, #{status}, #{lastLogin}, #{addTime}, #{updateTime})")
    @Options(useGeneratedKeys = true, keyProperty = "id")
    void addUser(User user);

    // 更新用户信息
    @Update("UPDATE User SET username = #{username}, password = #{password}, eloRating = #{eloRating}, " +
            "wins = #{wins}, losses = #{losses}, draws = #{draws}, status = #{status}, lastLogin = #{lastLogin} " +
            "WHERE id = #{id}")
    void updateUser(User user);

    // 根据用户名查询用户
    @Select("SELECT * FROM User WHERE username = #{username}")
    User getUserByUsername(@Param("username") String username);
    // 删除用户
    @Delete("DELETE FROM User WHERE id = #{id}")
    void deleteUser(@Param("id") Integer id);

    // 排行榜查询（使用索引优化）
    @Select("SELECT id, username, eloRating, wins, losses, " +
            "RANK() OVER (ORDER BY eloRating DESC) AS ranking " +
            "FROM User WHERE status = 1")
    List<UserRanking> selectLeaderboard();

    // 个人排名查询（高效实现）
    @Select("SELECT t.ranking, t.* FROM (" +
            "SELECT id, username, eloRating, wins, losses, " +
            "RANK() OVER (ORDER BY eloRating DESC) AS ranking " +
            "FROM User WHERE status = 1" +
            ") t WHERE t.id = #{userId}")
    UserRanking selectUserRanking(int userId);
}